package com.gitee.huxing.course.conc.conc03.tool;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @Description:
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.conc.conc03.tool
 * @ClassName: CyclicBarrierDemo2
 * @Author: huxingmale
 * @DateTime: 2021-08-26 0:13
 */
public class CyclicBarrierDemo2 {

    public static void main(String[] args) {
        int N = 4;
        CyclicBarrier barrier = new CyclicBarrier(N);
        for (int i = 0; i < N; i++) {
            new Thread(new write(barrier)).start();
        }
        try {
            Thread.sleep(10000);
        } catch (InterruptedException ex){
            ex.printStackTrace();
        }
        System.out.println("====> CyclicBarrier重用");
        for (int i = 0; i < N; i++) {
            new Thread(new write(barrier)).start();
        }
    }

    static class write extends Thread{

        private CyclicBarrier cyclicBarrier;

        public write(CyclicBarrier cyclicBarrier){
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            System.out.println("线程"+Thread.currentThread().getName()+"正在写入数据...");
            try {
                Thread.sleep(3000);      //以睡眠来模拟写入数据操作
                System.out.println("线程"+Thread.currentThread().getName() + "写入数据完毕，等待其他线程写入完毕");
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }catch(BrokenBarrierException e){
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"所有线程写入完毕，继续处理其他任务...");
        }
    }
}
